#include <stdio.h>
#include <sys/types.h>  
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/vfs.h>
#include "zlog.h"
#include "disk.h"

extern sys_cfg_info 		sys_cfg;
extern sys_runtime			sys_rt;

int creat_folder_of_save_file(sys_cfg_info *sys)
{
    time_t t;
	char s[50];
	char folder[FILE_PATH_LEN] = "";

    time(&t);
    struct tm *curr_time = localtime(&t);
	strftime(s, sizeof(s), "%04Y%02m%02d%H", curr_time);
	sprintf(folder, "%s%s%s", sys->disk_path, "/vdata/", s);
	if (opendir(folder) == NULL) {								//文件夹不存在，建立文件夹
    	if (mkdir(folder, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH) != 0) {
			sys->disk_data_save = OFF;								//失败则不保存数据
			printf("creat folder of save data %s failed!\n", folder);
			dzlog_error("creat folder of save data %s failed!", folder);
			perror("creat folder failed!");
			return FAILURE;
    	} else 
			printf("creat folder of save data successful!\n");
	}

	return 0;
}

uint8_t disk_size_check(sys_cfg_info *sys, sys_runtime *rt)									//监测磁盘空间
{
	uint32_t stat;
	struct statfs sfs;
	
	//statfs获得硬盘使用情况 模拟linux命令 df
	//path:位于需要查询信息的文件系统的文件路径名(不是设备名，是挂载点名称)。
	stat = statfs(sys->disk_path, &sfs);
	if(stat >= 0) {
		sys->disk_free_size = (float)(sfs.f_bfree / 1024.0) * (sfs.f_bsize / 1024.0); 		//转换成MB
		if (sys->debug == ON)
			printf("sfs.f_bfree is %ld blocks, sfs.f_bsize is %ld bytes, size check is %.2fMB\n", 
						sfs.f_bfree, sfs.f_bsize, sys->disk_free_size);
		if((sys->disk_free_size <= (float)sys->disk_warn_thrd) && (rt->disk_chk_flag == 0)) {
			if (sys->debug == ON)
				printf("disk ""%s"" size is %.2fMB,space not enough now!\n", 
						sys->disk_path, sys->disk_free_size);
			dzlog_notice("disk space is not enough now!");
			rt->disk_chk_flag = 1;
			return -1;
		} else if((sys->disk_free_size <= (float)sys->disk_alarm_thrd) && (rt->disk_chk_flag == 0)) {
			if (sys->debug == ON)
				printf("disk ""%s"" size is %.2fMB, space not enough now!\n", 
						sys->disk_path, sys->disk_free_size);
			dzlog_notice("disk space is not enough now!");
			rt->disk_chk_flag = 1;
			return -1;
		} else if ((sys->disk_free_size > (float)sys->disk_warn_thrd) && (rt->disk_chk_flag == 1))
			rt->disk_chk_flag = 0;
	} else
		printf("""%s"", No this disk!\n", sys->disk_path);

	return 0;
}


